package org.chinacareer.position.config;

import java.lang.reflect.Field;

import org.chinacareer.util.SpringContextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.alibaba.nacos.client.naming.core.HostReactor;
import com.netflix.loadbalancer.ServerListUpdater;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jerry
 * @ClassName:  MyPollingServerListUpdater   
 * @Description:TODO(描述这个类的作用)   
 * @date 2022年12月1日 下午3:09:10
 */
@Slf4j
public class NacosListener implements EventListener {

	private MyPollingServerListUpdater myListUpdater;

	private NacosNamingService namingService;

	private HostReactor hostReactor;

	@Override
	public void onEvent(Event event) {
		if(event.getClass().isAssignableFrom(NamingEvent.class)) {
			NamingEvent namingEvent = (NamingEvent) event;
			log.info("nacos监听事件消息:" + JSON.toJSONString(event));
			try {
				// 1.刷本地缓存
				namingService = (NacosNamingService) SpringContextUtils.getBean(NacosNamingService.class);
				Class cls = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
				Field field = cls.getDeclaredField("hostReactor");
				field.setAccessible(true);
				Object hostReactorValue = field.get(namingService);
				this.hostReactor = (HostReactor) hostReactorValue;
//			this.hostReactor.updateService(NamingUtils.getGroupedName(serviceName, groupName), "DEFAULT");
				this.hostReactor.updateService(namingEvent.getServiceName(), "DEFAULT");
				
				// 2.刷服务列表
				log.info("nacos监听事件，更新ribbon服务列表");
				myListUpdater = (MyPollingServerListUpdater) SpringContextUtils.getBean(MyPollingServerListUpdater.class);
				ServerListUpdater.UpdateAction updateAction = myListUpdater.getUpdateAction();
				if (updateAction != null) {
					updateAction.doUpdate();
				}
			} catch (Exception e) {
				log.error("Error in NacosListener onEvent:", e.getMessage());
			}
		}
	}
}
